// 文件路径: com.city.java.files.service.impl.FileUploadServiceImpl.java
package com.city.java.files.service.impl;

import com.city.java.files.controller.FileUploadController;
import com.city.java.files.controller.AnnouncementFileUploadController;
import com.city.java.files.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 文件上传服务实现类（支持普通图片和公告图片上传）
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    // 前端图片存储相对路径
    private static final String FRONTEND_PRODUCT_IMAGE_RELATIVE_PATH = "front/public/imgs/products";
    private static final String FRONTEND_ANNOUNCEMENT_IMAGE_RELATIVE_PATH = "front/public/imgs/announcements";

    @Value("${user.dir}")
    private String userDir;

    // 支持的图片格式
    private static final List<String> ALLOWED_IMAGE_TYPES = Arrays.asList(
        "image/jpeg",
        "image/png",
        "image/gif",
        "image/bmp",
        "image/webp"
    );

    @Override
    public String uploadImage(MultipartFile file) throws IOException {
        return uploadImageToPath(file, FRONTEND_PRODUCT_IMAGE_RELATIVE_PATH, "/imgs/products/");
    }

    @Override
    public FileUploadController.ImageUploadResult[] uploadImages(MultipartFile[] files) throws IOException {
        if (files == null || files.length == 0) {
            return new FileUploadController.ImageUploadResult[0];
        }

        FileUploadController.ImageUploadResult[] results = new FileUploadController.ImageUploadResult[files.length];
        for (int i = 0; i < files.length; i++) {
            String url = uploadImage(files[i]);
            results[i] = new FileUploadController.ImageUploadResult(url);
        }

        return results;
    }

    @Override
    public String uploadAnnouncementImage(MultipartFile file) throws IOException {
        return uploadImageToPath(file, FRONTEND_ANNOUNCEMENT_IMAGE_RELATIVE_PATH, "/imgs/announcements/");
    }

    @Override
    public AnnouncementFileUploadController.ImageUploadResult[] uploadAnnouncementImages(MultipartFile[] files) throws IOException {
        if (files == null || files.length == 0) {
            return new AnnouncementFileUploadController.ImageUploadResult[0];
        }

        AnnouncementFileUploadController.ImageUploadResult[] results = new AnnouncementFileUploadController.ImageUploadResult[files.length];
        for (int i = 0; i < files.length; i++) {
            String url = uploadAnnouncementImage(files[i]);
            results[i] = new AnnouncementFileUploadController.ImageUploadResult(url);
        }

        return results;
    }

    /**
     * 通用图片上传方法
     * @param file 上传的文件
     * @param relativePath 相对路径
     * @param urlPrefix URL前缀
     * @return 文件访问URL
     * @throws IOException IO异常
     */
    private String uploadImageToPath(MultipartFile file, String relativePath, String urlPrefix) throws IOException {
        // 参数校验
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !ALLOWED_IMAGE_TYPES.contains(contentType)) {
            throw new IllegalArgumentException("只支持上传图片文件（JPG、PNG、GIF、BMP、WEBP）");
        }

        // 检查文件大小（限制为2MB）
        if (file.getSize() > 2 * 1024 * 1024) {
            throw new IllegalArgumentException("图片文件大小不能超过2MB");
        }

        // 验证文件确实是图片
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null) {
                throw new IllegalArgumentException("文件不是有效的图片格式");
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("文件不是有效的图片格式: " + e.getMessage());
        }

        // 获取文件原始名称和扩展名
        String originalFilename = file.getOriginalFilename();
        String extension = getFileExtension(originalFilename);

        // 生成唯一的文件名
        String fileName = UUID.randomUUID().toString() + "." + extension;

        // 构建绝对路径
        String absolutePath = userDir + "/" + relativePath;

        // 确保目录存在
        File dir = new File(absolutePath);
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            if (!created) {
                throw new IOException("无法创建目录: " + absolutePath);
            }
        }

        // 构建完整的文件路径
        Path path = Paths.get(absolutePath, fileName);

        // 保存文件
        Files.write(path, file.getBytes());

        // 返回文件访问URL
        return urlPrefix + fileName;
    }

    /**
     * 获取文件扩展名
     * @param fileName 文件名
     * @return 扩展名
     */
    private String getFileExtension(String fileName) {
        if (fileName == null || fileName.lastIndexOf(".") == -1) {
            return "jpg"; // 默认扩展名
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    }
}
